import { DynamicModule, Global, Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';

const logFormat = winston.format.printf(
  ({ level, message, timestamp, context }) => {
    let msg = message;

    // 如果是对象，转成 JSON 字符串
    if (typeof message === 'object') {
      try {
        msg = JSON.stringify(message, null, 2); // 缩进2格更美观
      } catch (e) {
        msg = '[Circular Object]';
      }
    }

    return `[${timestamp}] [${level}]${context ? ' [' + context + ']' : ''} ${msg}`;
  },
);

@Module({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new winston.transports.File({
          dirname: 'D:\\kl-storage\\app-logs\\kl-mem-bridge', // 日志目录
          filename: 'app.log', // 日志文件
          level: 'info', // 日志级别
          format: winston.format.combine(
            winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }), // 毫秒
            logFormat,
          ),
        }),
        new winston.transports.Console({
          format: winston.format.combine(
            winston.format.colorize(),
            winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }), // 毫秒
            logFormat,
          ),
        }),
      ],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {
  static forRoot(): DynamicModule {
    return {
      global: true,
      module: AppModule,
      controllers: [AppController],
      providers: [AppService],
      exports: [AppService],
    };
  }
}

export { AppModule as MemBridgeModule, AppService as MemBridgeService };
